<?php

namespace App\Http\Controllers;

use App\Menu;
use App\Role;
use Illuminate\Http\Request;
use Workerman\Worker;

class HomeController extends Controller
{
    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        //$this->middleware('auth');
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        return $this->workman();
        //return view('home');
    }

    public function test()
    {
        $role = Role::find(5);
        $createPost = new Permission();
        $createPost->name         = 'create-post';
        $createPost->display_name = 'Create Posts'; // optional
// Allow a user to...
        $createPost->description  = 'create new blog posts'; // optional
        $createPost->save();

        $role->attachPermission($createPost);
    }

    public function phpTest()
    {
        $start = microtime();
        for($i = 0; $i < 10000; $i++)
        {
            $k = $i * $i;
        }
        $end = microtime();
        echo '<br/>'.($end - $start);
    }

    public function workman()
    {
        $menu = Menu::All()->toArray();
        $menus = json_encode($menu);
        // Create a Websocket server
        $ws_worker = new Worker("websocket://0.0.0.0:2346");

        // Emitted when new connection come
        $ws_worker->onConnect = function($connection)
        {
            echo "New connection\n";
        };

        // Emitted when data received
        $ws_worker->onMessage = function($connection, $data) use ($menus)
        {
            // Send hello $data
            $connection->send('hello ' . $menus);
        };

        // Emitted when connection closed
        $ws_worker->onClose = function($connection)
        {
            echo "Connection closed\n";
        };

        // Run worker
        Worker::runAll();
    }

    public function ws()
    {
        return view('ws');
    }
}
